﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc; 
using Web.Logs.Models;
using Zapi.Log.Db;

namespace Web.Logs.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return PartialView();
        }

        public ActionResult Data(string logger, string level, string serverName, int id = 0)
        {
            var islogger = string.IsNullOrWhiteSpace(logger);
            var islevel = string.IsNullOrWhiteSpace(level);
            var isserverName = string.IsNullOrWhiteSpace(serverName);
            using (LogsEf db = new LogsEf())
            {
                IQueryable<NLogs> nlogs = db.NLogs;
                var nlogJson = new NlogJson();
                nlogJson.MaxId = nlogs.Max(a => a.Id);
                if (id == 0)
                {
                    nlogs = nlogs.OrderByDescending(a => a.Id).Take(50);
                }
                else
                {
                    nlogs = nlogs.Where(a => (a.Id > id) && (islogger || a.Logger == logger) && (islevel || a.Level == level) && (isserverName || a.ServerName == serverName)).OrderByDescending(a => a.Id);
                }


                nlogJson.Data = nlogs.ToList().OrderBy(a => a.Id).Select(a => new
                {
                    Logged = a.Logged.ToString("yyyy-MM-dd HH:mm:ss"),
                    a.Logger,
                    a.Message,
                    a.Level,
                    a.ServerName,
                    a.Port,
                    a.Url
                });


                return Json(nlogJson, JsonRequestBehavior.AllowGet);
            }

        }
    }
}